{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 课后实践: requests\n",
    "+ 申请Azure帐户\n",
    "+ 使用Azure API key\n",
    "+ 使用requests模块\n",
    "+ 用代码取得API回应\n",
    "\n",
    "+ 写出代码，实现输入一个图片URL，可以识别出每个人脸的年龄、性别、眼镜的，加总成绩1分；列出每个人最可能的3种情绪及其判别值再加1分。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Microsoft Azure API(面部检测) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 1、导入需要的requests模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 先导入为们需要的模块\n",
    "import requests\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 2、申请Azure帐户,输入我们需要使用的Azure API key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "KEY = 'e969c474c0df4357a1f2a9dbf3b2329a'  # Replace with a valid Subscription Key here.在这里使用有效的订阅密钥替换。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 3、目标url [base url] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Base URL,  Request URL中 在 符号? 前面的部分\n",
    "BASE_URL = 'https://zoe-apiface.cognitiveservices.azure.com/face/v1.0/detect' \n",
    "\n",
    "# 输入自己的KEY值\n",
    "KEY = 'e969c474c0df4357a1f2a9dbf3b2329a'  # 在这里使用有效的订阅密钥替换。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 4、沿用API文档的示范代码,准备我们的headers和图片(数据)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 请求头\n",
    "# 沿用API的示范代碼，{subscription key}用KEY代入\n",
    "HEADERS = {\n",
    "    # Request headers\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': '{}'.format(KEY),\n",
    "}\n",
    "# 获取照片的URL\n",
    "img_url = 'http://picm.bbzhi.com/mingxingbizhi/feilunhaifeilunhaibizhi/star_starhk_141010_m.jpg' # 飞轮海4人"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 5、准备symbol ? 后面的数据\n",
    "+ 传参"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 传参\n",
    "data = {\n",
    "    'url': '{}'.format(img_url),\n",
    "}\n",
    "payload = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'flase',\n",
    "    'returnFaceAttributes': '{}'.format('age,gender,glasses,emotion'),# 年龄，性别，眼睛，情感  # 参数\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 6、requests发送我们请求\n",
    "\n",
    "* 注意请求方式(GET、POST、DELETE)\n",
    "* 注意json 和字典的差异 ,str vs dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': 'a0934bcf-e4fd-435e-b9d7-8f1e4b8c0dc3',\n",
       "  'faceRectangle': {'top': 165, 'left': 143, 'width': 65, 'height': 65},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 22.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.001,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.81,\n",
       "    'neutral': 0.187,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.002}}},\n",
       " {'faceId': 'd5099372-010d-4d2d-9a65-143775e18684',\n",
       "  'faceRectangle': {'top': 172, 'left': 289, 'width': 58, 'height': 58},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 22.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.985,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.014}}},\n",
       " {'faceId': '3331f6cc-b137-48e0-b174-2987a5d357ee',\n",
       "  'faceRectangle': {'top': 100, 'left': 425, 'width': 58, 'height': 58},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 21.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.98,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.019}}},\n",
       " {'faceId': 'b19d1a74-ec12-4536-b67f-a3dab1e8e4b2',\n",
       "  'faceRectangle': {'top': 85, 'left': 569, 'width': 56, 'height': 56},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 20.0,\n",
       "   'glasses': 'NoGlasses',\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}}]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 坑。参考http://docs.python-requests.org/zh_CN/latest/user/quickstart.html  【更加复杂的post请求】\n",
    "# 差別是 string 字串 vs. dict 字典\n",
    "# Azura 使用的是 data = json.dumps(payload) 或 json=payload，data = payload 会出错\n",
    "\n",
    "# json.dumps()，将字典格式转换成json格式\n",
    "\n",
    "# requests 请求\n",
    "r = requests.post(BASE_URL, data=json.dumps(data), params=payload, headers=HEADERS)  # HTTP? POST? 请求参数？\n",
    "\n",
    "# 获取状态码\n",
    "r.status_code  # 查看参数回传状态\n",
    "\n",
    "# 取得API回应\n",
    "results = r.json()  # 将回传数据转化成json格式\n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "+ 用pandas表格化数据\n",
    "+ 识别出每个人脸的年龄、性别、眼镜，列出每个人最可能的3种情绪。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>faceAttributes.age</th>\n",
       "      <th>faceAttributes.gender</th>\n",
       "      <th>faceAttributes.glasses</th>\n",
       "      <th>faceAttributes.emotion.contempt</th>\n",
       "      <th>faceAttributes.emotion.happiness</th>\n",
       "      <th>faceAttributes.emotion.neutral</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>22.0</td>\n",
       "      <td>male</td>\n",
       "      <td>NoGlasses</td>\n",
       "      <td>0.001</td>\n",
       "      <td>0.810</td>\n",
       "      <td>0.187</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>22.0</td>\n",
       "      <td>male</td>\n",
       "      <td>NoGlasses</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.985</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>21.0</td>\n",
       "      <td>male</td>\n",
       "      <td>NoGlasses</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.980</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>20.0</td>\n",
       "      <td>male</td>\n",
       "      <td>NoGlasses</td>\n",
       "      <td>0.000</td>\n",
       "      <td>1.000</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   faceAttributes.age faceAttributes.gender faceAttributes.glasses  \\\n",
       "0                22.0                  male              NoGlasses   \n",
       "1                22.0                  male              NoGlasses   \n",
       "2                21.0                  male              NoGlasses   \n",
       "3                20.0                  male              NoGlasses   \n",
       "\n",
       "   faceAttributes.emotion.contempt  faceAttributes.emotion.happiness  \\\n",
       "0                            0.001                             0.810   \n",
       "1                            0.000                             0.985   \n",
       "2                            0.000                             0.980   \n",
       "3                            0.000                             1.000   \n",
       "\n",
       "   faceAttributes.emotion.neutral  \n",
       "0                           0.187  \n",
       "1                           0.000  \n",
       "2                           0.000  \n",
       "3                           0.000  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd #导入pandas库 \n",
    "df = pd.json_normalize(results)# 升级pandas才能运行\n",
    "df\n",
    "df_1=df[['faceAttributes.age',\"faceAttributes.gender\",\"faceAttributes.glasses\",\"faceAttributes.emotion.contempt\",\"faceAttributes.emotion.happiness\",\"faceAttributes.emotion.neutral\"]]\n",
    "df_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
